package login;

import application.Seed;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
/*
 * This class's purpose is to take in login information in the form of a user
 * object, determine if is valid, and set appropriate fields in the user object
 * and pass it back to LoginServlet.  LoginServet can take that info and 
 * redirect the user to the appropriate page.
 * 
 * @author The Freds
 */
/**
 * 
 * @author Ben
 */
public class LoginDAO {

    static Connection currentCon = null;
    static ResultSet rs = null;
    static ResultSet rs2 = null;

        /**
	 * This method sets userAttemt's consectiveFails and valid fields as
         * well as respected database entry for consecutiveFails.
         * 
         * The following is a series of checks to validate a login:
         *  -searchQuery and the database connection are setup to see if the 
         *   username exists.  If so continue checks; if not fails is -1 and
         *   valid is false.
         *  -Now we know the username exists, so we check if it's locked.  If 
         *   it is locked, increment the fails for the records and return not
         *   valid with the incremented number of fails
         *  -Now we know the user isn't locked.  Now, if they password is wrong
         *   on there last attempt. The become locked, fails is incremented and
         *   returned, and valid is false.
         *  -Then if their password is incorrect, but it's not their last attempt
         *   1 or 2 fails is appropriately set and returned and valid is false
         *  -finally, if the password is correct valid is set to true and fails
         *   to zero.
         * 
         * @param userAttempt 
         * @return User that was passed in with consecutiveFails and valid
         * set appropriately.
         */
    public static User login(User userAttempt) {
        Statement stmt = null;
        userAttempt.setUsername(userAttempt.getUsername().replaceAll("'","''"));
        String usernameInput = userAttempt.getUsername();
        String passwordInput = userAttempt.getPassword();
        String searchQuery = "select * from users where uname='" + usernameInput + "'";
        

        try {
            currentCon = ConnectionManager.getConnection();
            stmt = currentCon.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
            rs = stmt.executeQuery(searchQuery);
            boolean userExists = rs.first();
            if (!userExists) {//no username in database
                userAttempt.setValid(false);
                userAttempt.setFails(-1);
            } else {//user in database
                String password = rs.getObject("password").toString();
                boolean isLocked = rs.getBoolean("isLocked");
                userAttempt.setIsAdmin(rs.getBoolean("isAdmin"));
                userAttempt.setFirstName(rs.getObject("firstName").toString());
                userAttempt.setLastName(rs.getObject("lastName").toString());
                userAttempt.setEmail(rs.getObject("email").toString());
                userAttempt.setClimateZone(rs.getObject("climateZone").toString());
                userAttempt.setStreet1(rs.getObject("street1").toString());
                userAttempt.setStreet2(rs.getObject("Street2").toString());
                userAttempt.setState(rs.getObject("stateMail").toString());
                userAttempt.setZip(rs.getObject("zip").toString());
                userAttempt.setInterests(rs.getObject("interests").toString());
                userAttempt.setCity(rs.getObject("city").toString());
                userAttempt.setID((Integer)rs.getObject("sr_no"));
                //Add all the other fields
                
                int fails = rs.getInt("consecutiveFails");
                if(isLocked){//user is already locked
                    fails++;
                    userAttempt.setFails(fails);
                    rs.updateInt("consecutiveFails", fails);
                    userAttempt.setFails(fails);
                    userAttempt.setValid(false);
                }else{//user entered invalid password on lass attempt
                    if (!passwordInput.equals(password) && fails==2) {
                        fails++;
                        userAttempt.setFails(fails);
                        rs.updateInt("consecutiveFails", fails);
                        userAttempt.setFails(fails);
                        rs.updateBoolean("isLocked", true);
                        userAttempt.setValid(false);
                    }else{//user entered invalid password but has more attempts
                        if (!passwordInput.equals(password)){
                        fails++;
                        userAttempt.setFails(fails);
                        rs.updateInt("consecutiveFails", fails);
                        userAttempt.setFails(fails);
                        userAttempt.setValid(false);
                        }else{//they're login was valid and not locked
                            fails=0;
                            userAttempt.setFails(fails);
                            rs.updateInt("consecutiveFails", fails);
                            userAttempt.setFails(fails);
                            userAttempt.setValid(true);
                        }
                    }
                }
                rs.updateRow();//this updates the database with your changes to the row.
            }
        } catch (Exception ex) {
            System.out.println("connection bad-probably database url" + ex);
        }
        return userAttempt;
    }
}
